package coap.server;

import coap.messages.*;

import java.net.InetAddress;
import java.util.HashMap;

public class CoAPServer{
	
    ServerSession session = null;
    HashMap<String, byte[]> table = new HashMap<String, byte[]>();

    //private int debug = 0;
    public void handleRequest(Message msg,  InetAddress sender, int senderPort){
        System.out.println("get "+msg);
        switch(msg.getCode()){
            case MethodCodes.GET:
                String key = msg.getOption(OptionNumber.UriPath).getStringValue();
                if(table.containsKey(key)){
                    Message reply = new Message(MessageType.Acknowledgement, ResponseCodes.Content, msg.getMessageID(), table.get(key));
                    reply.addOption(msg.getOption(OptionNumber.Token));
                    session.sendMessage(reply, sender, senderPort);
                }
                else{
                    Message reply = new Message(MessageType.Acknowledgement, ResponseCodes.NotFound, msg.getMessageID(), new byte[0]);
                    reply.addOption(msg.getOption(OptionNumber.Token));
                    session.sendMessage(reply, sender, senderPort);
                }
                break;
            case MethodCodes.PUT:
                key = msg.getOption(OptionNumber.UriPath).getStringValue();
                if(table.containsKey(key)){
                    table.put(key, msg.getPayLoad());
                    Message reply = new Message(MessageType.Acknowledgement, ResponseCodes.Changed, msg.getMessageID(), new byte[0]);
                    reply.addOption(msg.getOption(OptionNumber.Token));
                    session.sendMessage(reply, sender, senderPort);
                }
                else{
                    table.put(key, msg.getPayLoad());
                    Message reply = new Message(MessageType.Acknowledgement, ResponseCodes.Created, msg.getMessageID(), new byte[0]);
                    reply.addOption(msg.getOption(OptionNumber.Token));
                    session.sendMessage(reply, sender, senderPort);
                }
                break;
        }
	}

    public synchronized void handleAck(Message ack){
        System.out.println("ack "+ack);
    }

    public synchronized void failed(Message originalMessage){
        System.out.println("failed "+originalMessage);
    }


    public CoAPServer(){
		try {
			session = new ServerSession(this);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) throws Exception{
		CoAPServer server = new CoAPServer();
		System.out.println("CoAP server started");
		while(true){
			Thread.sleep(1000);
		}
	}
}
